package com.example.interceptor;

import com.example.feign.PermissionFeignClient;
import com.example.util.UserContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.context.annotation.Lazy;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.web.context.request.ServletRequestAttributes;


//=============自己的思考结合AI生成的代码 并改写AI代码==============
@Slf4j
@Component
public class PermissionInterceptor implements HandlerInterceptor {

    @Lazy
    @Autowired
    private PermissionFeignClient permissionFeignClient;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //获取请求路径
        String path = request.getRequestURI();

        //登录注册接口不进行权限验证
        if (path.startsWith("/user/login") || path.startsWith("/user/register")) {
            log.info("登录注册接口不进行权限验证");
            return true;
        }

        //获取当前用户ID和角色码
        Long currentUserId = UserContext.getCurrentUserId();
        log.info("当前用户ID: {}", currentUserId);
        String roleCode = permissionFeignClient.getUserRoleCode(currentUserId);

        //将角色码存入请求属性
        request.setAttribute("currentRole", roleCode);
        log.info("当前用户角色码: {}", roleCode);
        return true;
    }
}
